// pages/dohelp/index.js

const util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentindex:0,
    swiper_background: [
      'cloud://cloud1-5glocnmp62950062.636c-cloud1-5glocnmp62950062-1310108215/swiperpic1.png', 
    'cloud://cloud1-5glocnmp62950062.636c-cloud1-5glocnmp62950062-1310108215/ads/work.png',
    'cloud://cloud1-5glocnmp62950062.636c-cloud1-5glocnmp62950062-1310108215/ads/org.png'],
    tablist:['最新发布','急！！！','长期合作','与我相关'],
    tasklist:[],
    currenttasklist:[],
    openid:'',
    currentkey:'',
    userInfo:{},
    //滑动相关
    startX:'',
        startY:'', 
        endX:'', 
        endY:'',
        myInde:'',
        card_leftid:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      openid: wx.getStorageSync('OPENID'),
      userInfo: wx.getStorageSync('userInfo')
    })
    this.getTaskList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  changetab: function(e){
    let index = e.currentTarget.dataset.index
    this.showcurrentList(index)
  },
  showcurrentList(index){
    let tasklist = this.data.tasklist
    if(index==0){
      tasklist = tasklist.filter(item=>{
        return !item.status
      })
    }
    if(index==1){
      tasklist = tasklist.filter(item=>{
        return item.urgent&&!item.status
      })
    }
    if(index==2){
      tasklist = tasklist.filter(item=>{
        return item.longtime&&!item.status
      })
    }
    if(index==3){
      tasklist = tasklist.filter(item=>{
        return item.mine||item.myRec
      })
    }
    
    this.setData({
      currentindex: index,
      currenttasklist:tasklist
    })
  },
  getTaskList(){
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.init({env: 'cloud1-5glocnmp62950062'})
    wx.cloud.callFunction({
      name: 'getTasklist',
      success: (res)=> {
        wx.hideLoading()
        let tasklist = res.result.tasklist.list.reverse().map(item=>{
          item.mine = (item._openid==this.data.openid)
          if(item.applyData.length>0){
            item.myRec = (item.applyData[0].recipientid==this.data.openid)
          }
          item.title = util.subStrFormat(item.title,16)
          return item
        }).filter(item=>{
          return item.applyData.length==0 || item.mine || item.myRec
        })
          this.setData({
          tasklist:tasklist,
        })
        this.showcurrentList(this.data.currentindex)
      },
      fail: function (err) {
        wx.showToast({
          title: '获取数据失败，请稍后再试',
          icon: 'none',
        })
        console.error(err)
      },
      complete: res=>{
      }
    })
  },
  getsearchResult(e){
    let searchkey = e.detail
    if(searchkey===''){
      this.getTaskList()
      return
    }
    this.setData({
      currentkey:searchkey
    })
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.init({env: 'cloud1-5glocnmp62950062'})
    wx.cloud.callFunction({
      name: 'searchTask',
      data:{key: this.data.currentkey},
      success: (res)=> {
        wx.hideLoading()
        let tasklist = res.result.tasklist.list.reverse().map(item=>{
          item.mine = (item._openid==this.data.openid)
          if(item.applyData.length>0){
            item.myRec = (item.applyData[0].recipientid==this.data.openid)
          }
          item.title = util.subStrFormat(item.title,16)
          return item
        }).filter(item=>{
          return (item.applyData.length==0 || item.mine || item.myRec) && !item.status
        })
          this.setData({
          tasklist:tasklist,
        })
        this.showcurrentList(this.data.currentindex)
    
      },
      fail: function (err) {
        wx.showToast({
          title: '获取数据失败，请稍后再试',
          icon: 'none',
        })
      },
      complete: res=>{
      }
    })
    
  },
  showFile:function(e){
    let fileID = e.currentTarget.dataset.fileid
    let fileType = e.currentTarget.dataset.filetype
    //下载文件
    wx.cloud.downloadFile({
      fileID: fileID,
      success: res => { 
        console.log("文件下载成功",res);
        //打开文件
        const filePath = res.tempFilePath
        if(fileType=='image'){
          wx.previewImage({
            urls: [filePath],
            success: (res) => {
              console.log('文件打开成功',res)
            },
            fail:(err)=>{
              console.error(err)
            }
          })
        }else{
        wx.openDocument({
          filePath: filePath,
          success: (res) => {
            console.log('文件打开成功',res)
          },
          fail:(res)=>{
            wx.showToast({
              title: '文件格式错误！',
              icon:'warning'
            })
            console.error(res)
          }
        })
        }

      }
  })
},
contact: async function(e){
let taskid = e.currentTarget.dataset.taskid
let checkResult = await this.checkApplypeople(taskid)
if(checkResult.length!==0){
  wx.showToast({
    title: '啊哦，这个任务刚才被领取了',
    icon:'none',
    success:(res)=>{
      setTimeout(() => {
        this.getTaskList()
      }, 2000);
      
    }
  })
  return
}
console.log(checkResult)

let taskopenid = e.currentTarget.dataset.openid,
taskwxid = e.currentTarget.dataset.wxid,
tasknickname = e.currentTarget.dataset.nickname,
openid = wx.getStorageSync('OPENID')
if(taskopenid==openid){
  wx.showToast({
    title: '这是您自己的任务！',
    icon:'none'
  })
  return
}else{
  wx.showModal({
    cancelColor: 'cancelColor',
    title: '请您输入手机号确认接受该任务',
    editable:true,
    success: (res) => {
      if (res.confirm) {
        wx.cloud.database().collection('applyTask').add({
          data:{
            publishnickname: tasknickname,
            recipientnickname:this.data.userInfo.nickname,
            taskid: taskid,
            publisherid: taskopenid,
            publishwxid:taskwxid,
            recipientid:openid,
            recipientwxid:res.content,
            status:0
          },
          success:(res)=>{
            console.log(res)
            this.getTaskList()
          }
        })
      } else {
        console.log('用户点击取消')
      }
    }
  })
}
},
delTask: function(e) {
  let taskid = e.currentTarget.dataset.taskid
  wx.showModal({
    title:'提示',
    content:'你确定删除这个任务吗',
    showCancel: true,
    cancelText: '取消',
    confirmText: '确定',
    success: (result) => {
      if (result.confirm) {
        wx.cloud.database().collection('tasklist').where({_id:taskid}).remove({
          success:res=>{
            wx.showToast({
              title: '删除成功',
            })
            this.getTaskList()
          }
        })
      }
    },
  })
},
showRecipient: function(e){
  let {recipientwxid,recipientnickname} = e.currentTarget.dataset.applydata
  let  taskid = e.currentTarget.dataset.taskid
  wx.showModal({
    title: `用户${recipientnickname}接受了你的任务`,
    content:`TA的手机号是：${recipientwxid}`,
    success:(res)=>{
      if(res.confirm){
        wx.setClipboardData({
          data: recipientwxid,
          success:(res)=>{
            wx.showToast({
              title: '已为您复制TA的手机号',
              icon:'none'
            })
          }
        })
      }
    }
  })
},
showPublisher: function(e){
  let {publishwxid,publishnickname} = e.currentTarget.dataset.applydata
  let  taskid = e.currentTarget.dataset.taskid
  wx.showModal({
    title: `您已接受${publishnickname}的任务`,
    content:`TA的手机号是：${publishwxid}`,
    success:(res)=>{
      if(res.confirm){
        wx.setClipboardData({
          data: publishwxid,
          success:(res)=>{
            wx.showToast({
              title: '已为您复制TA的手机号',
              icon:'none'
            })
          }
        })
      }
    }
  })
},
checkApplypeople: function(taskid){
  return new Promise((resolve,reject)=>{
      wx.cloud.database().collection('applyTask').where({taskid:taskid}).get({
    success:(res)=>{
      resolve(res.data)
    },
    fail:(err)=>{
      reject(err)
    }
  })
  })

},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getTaskList()
    wx.stopPullDownRefresh()
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
      //手指触摸开始 
      drawerStart: function(e) {
        let touch = e.touches[0];
        this.setData({
            card_leftid:e.currentTarget.dataset.card_leftid,
            startX :touch.clientX,
            startY :touch.clientY
        })
    },  
    //手指触摸滑动离开
    drawerMove: function(e) {
      let touch = e.touches[0];
        this.setData({
            endX : touch.clientX,
            endY : touch.clientY,
        })
      this.drawerEnd();//执行滑动效果
    }, 
        //滑动效果
        drawerEnd: function(e) {
          let self = this;
          //从右往左
          let { endX, startX, card_leftid} = this.data
          let myInde = card_leftid;
          if ((endX - startX) <0) {
                  self.setData({
                      myInde: myInde
                  })
          } else { //从左往右

                  self.setData({
                      myInde: ''
                  })
           }
      },
      republishTask:function(e){
        let applyid = e.currentTarget.dataset.id
        wx.cloud.database().collection('applyTask').doc(applyid).remove({
          success: (res)=>{
            wx.showToast({
              title: '设置成功',
              success: (res)=>{
              this.getTaskList()
            }
            },
            
            )
          }
        })
      },
      doneTask: function(e){
        let taskid = e.currentTarget.dataset.id
        wx.cloud.database().collection('tasklist').doc(taskid).update({
          data:{
            status:true
          },
          success: (res)=> {
            wx.showToast({
              title: '设置成功',
              success:(res)=>{
                this.getTaskList()
              }
            })
          }
        })
      },
  newTask: function(){
    wx.navigateTo({
      url: '/pages/publishTask/index',
    })
  }
})